package api;

import Dao.Blog;
import Dao.BlogDao;
import Dao.User;
import Dao.UserDao;
import com.fasterxml.jackson.databind.ObjectMapper;
import common.Common;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/details")
public class DetailsServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");

        User user = Common.checkLoginStatus(req);
        if (user == null){
            resp.setStatus(403);
            return;
        }

        String blogId = req.getParameter("blogId");

        BlogDao blogDao = new BlogDao();
        UserDao userDao = new UserDao();

        Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
        User author = userDao.selectById(blog.getUserId());
        blog.setIsAuthor(author.getUserId() == user.getUserId() ? 1 : 0);

        resp.getWriter().write(objectMapper.writeValueAsString(blog));

    }
}
